#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
文件打开对话框模块
提供文件选择和导入设置
"""

import os
import logging
from pathlib import Path
from typing import Optional, List, Tuple

from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
                              QLineEdit, QPushButton, QFileDialog, QComboBox,
                              QGroupBox, QFormLayout, QTabWidget, QWidget,
                              QCheckBox, QGridLayout, QSpinBox, QDialogButtonBox)

from config.constants import CSV_DELIMITERS, DEFAULT_ENCODINGS, FILE_TYPES
from config.settings import settings
from core.i18n import tr


# 初始化日志记录器
logger = logging.getLogger("file_open")


class FileOpenDialog(QDialog):
    """文件打开对话框，支持CSV/Parquet文件导入设置"""
    
    # 信号定义
    file_selected = Signal(str, str, dict)  # 文件路径, 表名, 选项字典
    
    def __init__(self, parent=None):
        """初始化文件打开对话框
        
        Args:
            parent: 父窗口
        """
        super().__init__(parent)
        self.setWindowTitle(tr("file_open_title", "打开文件"))
        self.resize(600, 400)
        self._init_ui()
        
    def _init_ui(self):
        """初始化UI"""
        # 主布局
        layout = QVBoxLayout(self)
        
        # 文件选择部分
        file_group = QGroupBox(tr("file_selection", "文件选择"))
        file_layout = QHBoxLayout()
        
        # 文件路径输入框
        self.file_path_edit = QLineEdit()
        self.file_path_edit.setPlaceholderText(tr("file_path_placeholder", "文件路径..."))
        self.file_path_edit.textChanged.connect(self._update_ui_state)
        
        # 浏览按钮
        browse_button = QPushButton(tr("button_browse", "浏览..."))
        browse_button.clicked.connect(self._browse_file)
        
        file_layout.addWidget(self.file_path_edit)
        file_layout.addWidget(browse_button)
        file_group.setLayout(file_layout)
        layout.addWidget(file_group)
        
        # 表名设置
        table_group = QGroupBox(tr("table_name_settings", "表名设置"))
        table_layout = QFormLayout()
        
        # 表名输入框
        self.table_name_edit = QLineEdit()
        self.table_name_edit.setPlaceholderText(tr("table_name_placeholder", "留空将使用文件名"))
        table_layout.addRow(tr("file_table_name", "表名:"), self.table_name_edit)
        
        table_group.setLayout(table_layout)
        layout.addWidget(table_group)
        
        # 导入选项（使用选项卡）
        options_tab = QTabWidget()
        
        # CSV选项卡
        csv_tab = QWidget()
        csv_layout = QFormLayout(csv_tab)
        
        # 分隔符选择
        self.delimiter_combo = QComboBox()
        for delimiter in CSV_DELIMITERS:
            display_text = delimiter
            if delimiter == ",":
                display_text = tr("delimiter_comma", "逗号 (,)")
            elif delimiter == ";":
                display_text = tr("delimiter_semicolon", "分号 (;)")
            elif delimiter == "|":
                display_text = tr("delimiter_pipe", "竖线 (|)")
            elif delimiter == "\t":
                display_text = tr("delimiter_tab", "制表符 (\\t)")
                
            self.delimiter_combo.addItem(display_text, delimiter)
            
        # 默认选择逗号
        self.delimiter_combo.setCurrentIndex(0)
        csv_layout.addRow(tr("file_delimiter", "分隔符:"), self.delimiter_combo)
        
        # 编码选择
        self.encoding_combo = QComboBox()
        for encoding in DEFAULT_ENCODINGS:
            self.encoding_combo.addItem(encoding)
        csv_layout.addRow(tr("file_encoding", "编码:"), self.encoding_combo)
        
        # 表头设置
        self.header_check = QCheckBox(tr("file_header_row", "包含表头行"))
        self.header_check.setChecked(True)
        csv_layout.addRow("", self.header_check)
        
        # 预览行数
        self.preview_spin = QSpinBox()
        self.preview_spin.setRange(10, 1000)
        self.preview_spin.setValue(100)
        self.preview_spin.setSingleStep(10)
        csv_layout.addRow(tr("file_preview_rows", "预览行数:"), self.preview_spin)
        
        # Parquet选项卡
        parquet_tab = QWidget()
        parquet_layout = QFormLayout(parquet_tab)
        
        # Parquet预览行数
        self.parquet_preview_spin = QSpinBox()
        self.parquet_preview_spin.setRange(10, 1000)
        self.parquet_preview_spin.setValue(100)
        self.parquet_preview_spin.setSingleStep(10)
        parquet_layout.addRow(tr("file_preview_rows", "预览行数:"), self.parquet_preview_spin)
        
        # 添加选项卡
        options_tab.addTab(csv_tab, tr("file_csv_options", "CSV选项"))
        options_tab.addTab(parquet_tab, tr("file_parquet_options", "Parquet选项"))
        
        layout.addWidget(options_tab)
        
        # 最近打开文件
        recent_group = QGroupBox(tr("file_recent_files", "最近打开的文件"))
        recent_layout = QVBoxLayout()
        
        # 最近文件列表
        self.recent_combo = QComboBox()
        self.recent_combo.setMaxVisibleItems(10)
        self.recent_combo.currentIndexChanged.connect(self._recent_file_selected)
        
        # 加载最近文件
        self._load_recent_files()
        
        recent_layout.addWidget(self.recent_combo)
        recent_group.setLayout(recent_layout)
        layout.addWidget(recent_group)
        
        # 按钮
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        
        self.ok_button = button_box.button(QDialogButtonBox.Ok)
        self.ok_button.setText(tr("button_open", "打开"))
        self.ok_button.setEnabled(False)
        
        layout.addWidget(button_box)
        
    def _browse_file(self):
        """浏览文件"""
        # 构建文件过滤器
        filters = []
        
        for file_type, info in FILE_TYPES.items():
            filters.append(info["description"])
            
        filters.append(tr("file_all_files", "所有文件 (*.*)"))
        
        # 显示文件对话框
        options = QFileDialog.Options()
        file_path, _ = QFileDialog.getOpenFileName(
            self, 
            tr("file_select_dialog", "选择文件"), 
            "", 
            ";;".join(filters),
            options=options
        )
        
        if file_path:
            self.file_path_edit.setText(file_path)
            
            # 设置自动表名
            table_name = Path(file_path).stem.replace(' ', '_').replace('-', '_')
            self.table_name_edit.setText(table_name)
    
    def _load_recent_files(self):
        """加载最近打开的文件"""
        self.recent_combo.clear()
        
        self.recent_combo.addItem(tr("file_recent_select", "选择最近文件..."), "")
        
        # 获取最近文件列表
        recent_files = settings.get_recent_files()
        
        for file_path in recent_files:
            if os.path.exists(file_path):
                file_name = os.path.basename(file_path)
                self.recent_combo.addItem(file_name, file_path)
                
    def _recent_file_selected(self, index):
        """处理最近文件选择
        
        Args:
            index: 选择的索引
        """
        if index <= 0:
            return
            
        file_path = self.recent_combo.itemData(index)
        if file_path:
            self.file_path_edit.setText(file_path)
            
            # 设置自动表名
            table_name = Path(file_path).stem.replace(' ', '_').replace('-', '_')
            self.table_name_edit.setText(table_name)
    
    def _update_ui_state(self):
        """更新UI状态"""
        file_path = self.file_path_edit.text().strip()
        self.ok_button.setEnabled(os.path.exists(file_path))
        
    def accept(self):
        """接受对话框"""
        file_path = self.file_path_edit.text().strip()
        
        if not os.path.exists(file_path):
            return
            
        # 获取表名
        table_name = self.table_name_edit.text().strip()
        
        # 确定文件类型
        file_type = None
        suffix = Path(file_path).suffix.lower()
        
        for type_name, info in FILE_TYPES.items():
            if suffix in info["extensions"]:
                file_type = type_name
                break
                
        # 如果无法确定文件类型
        if not file_type:
            logger.warning(f"无法确定文件类型: {suffix}")
            # 默认作为CSV处理
            file_type = "CSV"
            
        # 获取导入选项
        options = {}
        
        if file_type == "CSV":
            # CSV特有选项
            delimiter_index = self.delimiter_combo.currentIndex()
            options["delimiter"] = self.delimiter_combo.itemData(delimiter_index)
            
            options["encoding"] = self.encoding_combo.currentText()
            options["header"] = self.header_check.isChecked()
            options["preview_rows"] = self.preview_spin.value()
        elif file_type == "PARQUET":
            # Parquet特有选项
            options["preview_rows"] = self.parquet_preview_spin.value()
            
        # 发出信号
        self.file_selected.emit(file_path, table_name, options)
        
        # 添加到最近文件
        settings.add_recent_file(file_path)
        settings.save_settings()
        
        super().accept()
